package com.jinbai.service;

import com.jinbai.data_object.TidToCountDO;
import com.jinbai.data_object.TrackDO;
import com.jinbai.repo.RelationRepo;
import com.jinbai.repo.TrackRepo;
import com.jinbai.util.Log;
import com.jinbai.view_object.ListTrackVO;
import com.jinbai.view_object.PaginationView;
import com.jinbai.view_object.StudioTrackListView;
import com.jinbai.view_object.UserVO;

import java.util.*;

public class TrackService {
    private final TrackRepo trackRepo = new TrackRepo();
    private final RelationRepo relationRepo = new RelationRepo();

    public StudioTrackListView listOfUser(UserVO currentUser, int page) {
        StudioTrackListView resultView = new StudioTrackListView();
        resultView.setCurrentUser(currentUser);

        // 规定每页查询20条
        int countPerPage = 5;
        int offset = (page - 1) * countPerPage;

        List<TrackDO> listTrackDOS = trackRepo.selectListByUidLimitOffset(currentUser.getUid(), countPerPage, offset);
        Log.println("从数据库中查询到的结果：" + listTrackDOS);
        if (!listTrackDOS.isEmpty()) {
            Log.println("结果不为空，需要继续查询关联数量");
            // 根据结果，查询每个track对应的refCount（引用次数）
            //    需要先从list中得到每一个tid
            List<Integer> tidList = new LinkedList<>();
            for (TrackDO trackDO : listTrackDOS) {
                tidList.add(trackDO.getTid());
            }
            //     依据这些tid执行sql从relations得到需要的结果Map<tid, refCount>
            Map<Integer, Integer> tidToRefCountMap = new HashMap<>();
            List<TidToCountDO> tidToCountDOList = RelationRepo.selectCountByTidListGroupByTidList(tidList);
            Log.println("查询relations表得到的结果" + tidToCountDOList);

            for (TidToCountDO tidToCountDO : tidToCountDOList) {
                tidToRefCountMap.put(tidToCountDO.getTid(), tidToCountDO.getRefCount());
            }
            Log.println("tid to refCount Map: " + tidToRefCountMap);

            List<ListTrackVO> listTrackVOS = new LinkedList<>();
            for (TrackDO trackDO : listTrackDOS) {
                listTrackVOS.add(new ListTrackVO(trackDO, tidToRefCountMap.getOrDefault(trackDO.getTid(), 0)));
            }
            Log.println("转换后的结果：" + listTrackVOS);
            resultView.setTrackVOList(listTrackVOS);
        } else {
            Log.println("结果为空，不需要查询关联数量");
//            resultView.setTrackVOList(null);
        }


        // 查询页码信息
        int count = trackRepo.selectCountByUid(currentUser.getUid());
        int totalPage = count / countPerPage;
        // 向上取整
        if (count % countPerPage > 0) {
            totalPage ++;
        }
        PaginationView paginationView = new PaginationView();
        paginationView.setCountPerPage(countPerPage);
        paginationView.setCurrentPage(page);
        paginationView.setTotalPage(totalPage);
        resultView.setPaginationView(paginationView);
        return resultView;
    }
}
